package kr.co.boogui.service;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import kr.co.boogui.dao.MovieDAO;
import kr.co.boogui.model.MovieVO;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;


public class MovieRegistryService {
	
	// 영화 등록 (form 값 입력)
	public static boolean movieFrmRegistry(MultipartRequest mreq) throws ServletException, IOException {
		boolean result = false;
		MovieVO mov = new MovieVO();	
		mov.setTitle(mreq.getParameter("title"));
		mov.setGenre1(mreq.getParameter("genre1"));
		mov.setGenre2(mreq.getParameter("genre2"));
		mov.setGenre3(mreq.getParameter("genre3"));
		mov.setDirector(mreq.getParameter("director"));
		mov.setActor1(mreq.getParameter("actor1"));
		mov.setActor2(mreq.getParameter("actor2"));
		mov.setActor3(mreq.getParameter("actor3"));
		mov.setRate(mreq.getParameter("rate"));
		mov.setRunningtime(mreq.getParameter("runningtime"));
		mov.setPlaydate(mreq.getParameter("playdate"));
		mov.setSynop(mreq.getParameter("synop"));	
		
		if(MovieDAO.insertMovie(mov)){
			result = true;
		} else {
			result = false;
		}
		return result;
	}
	// 파일명
	public static String renameFile() {
		return MovieDAO.readMovno();
	}
	
	// 영화 등록 (파일, 정보)
	public static boolean movieRegistry(HttpServletRequest req) {
		boolean result = false;
		
		String fpath = "d:/CDN/boogui/poster/";		
		int size = 1024*1024*5;		
		try {
			MultipartRequest mreq = new MultipartRequest(req, fpath, size, "UTF-8");
			Enumeration formNames = mreq.getFileNames();  // 폼의 이름 반환
			String formName = (String)formNames.nextElement(); // 자료가 많을 경우엔 while 문을 사용
			String fileName = mreq.getFilesystemName(formName); // 파일의 이름 얻기
			if(fileName == null) {   // 파일이 업로드 되지 않았을때
				System.out.println("fail");
			} else {  // 파일이 업로드 되었을때
				if (movieFrmRegistry(mreq)){
					result = true;
					String fname = renameFile();
					File oldFile = new File(fpath + fileName);
					File file = new File(fpath + fname + ".jpg");
					oldFile.renameTo(file);
				}
			 } // end if
		 } catch(Exception e) {
			 e.printStackTrace();
		 } 
		
		return result;
	}
	
	// 포스터 임시저장
	public static String tmpPoster(HttpServletRequest req) {
		String result = "";		
		String fpath = "d:/CDN/boogui/temp/";		
		int size = 1024*1024*5;
		try {
			MultipartRequest mreq = new MultipartRequest(req, fpath, size, "UTF-8");
			Enumeration formNames = mreq.getFileNames();
			String formName = (String)formNames.nextElement();
			String fileName = mreq.getFilesystemName(formName);
			if(fileName == null) {
				System.out.println("fail");
			} else {			
				result = fileName;
			 } // end if
		 } catch(Exception e) {
			 e.printStackTrace();
		 } 
		
		return result;
	}
}
